package cn.cycleif.admin.service;

import cn.cycleif.app.mapper.RoleMapper;
import cn.cycleif.app.mapper.UserRoleMapper;
import cn.cycleif.app.service.MenuService;
import cn.cycleif.entity.Menu;
import cn.cycleif.entity.Role;
import cn.cycleif.entity.UserRole;
import cn.cycleif.util.R;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Date: 25/1/27-15:53
 * @Desc:
 */
@Service
@RequiredArgsConstructor
public class AdminRoleService extends ServiceImpl<RoleMapper, Role> {

  private final RoleMapper     roleMapper;
  private final UserRoleMapper userRoleMapper;
  private final MenuService    menuService;

  public R<String> assignRoles(Integer[] roleIds, Integer userId) {

    for (Integer roleId : roleIds) {
      UserRole userRole = new UserRole();

      userRole.setUserId(userId);
      userRole.setRoleId(roleId);
      userRoleMapper.insert(userRole);
    }

    return R.success();
  }

  public R<String> insert(String name, String remark) {
    Role one = roleMapper.selectOne(
        new LambdaQueryWrapper<Role>().eq(Role::getName, name)
    );
    if (one != null) {
      return R.error("角色名已存在");
    }
    Role role = new Role();
    role.setName(name);
    role.setRemark(remark);
    roleMapper.insert(role);

    return R.success();
  }

  public R<String> updateRole(Role role) {
    int update = roleMapper.updateById(role);
    return R.success(update + "");
  }

  public R<Object> detail(Integer id) {
    Role byId = roleMapper.selectById(id);
    if (byId == null) return R.error("角色不存在");
    List<String> list = new ArrayList<>();
    // 查询角色权限
    R<List<Menu>> menus = menuService.getMenusByRoleId(byId.getId());
    for (Menu menu : menus.getData()) list.add(menu.getType());
    Map<String, Object> map = new HashMap<>();
    map.put("menus", list);
    map.put("basic", byId);
    return R.success(map);
  }
}
